package com.example.baselibrary.net.http

import android.util.Log
import com.example.baselibrary.net.http.interceptor.AddCookiesInterceptor
import com.example.baselibrary.net.http.interceptor.ReceivedCookiesInterceptor
import com.example.baselibrary.utils.SPUtils
import com.example.baselibrary.utils.SpConstant
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Created by yechaoa on 2021/2/4.
 * Describe :
 */
object RetrofitClient {

    private const val CALL_TIMEOUT = 20L
    private const val CONNECT_TIMEOUT = 30L
    private const val IO_TIMEOUT = 30L

    private var apiService: Api

    fun getApiService(): Api {
        return apiService
    }

    init {
        val mTokenInterceptor = Interceptor { chain ->
            var originalRequest: Request = chain.request()
            //添加header
            originalRequest = originalRequest.newBuilder()
//                .header("sign", MyTimeUtils.get10TimeLong().toString())
                .build()
            if (SPUtils.getInstance().myUserInfo != null) {
                val authorised = originalRequest.newBuilder()
//                    .header("token", SPUtils.getInstance().myUserInfo.token)
                    .header("Accept", "application/json")
                    .header("device-model", SpConstant.Device_Mode)
                    .header("device-unique-code", SpConstant.Device_Unique_Code)
                    .build()
                chain.proceed(authorised)
            } else {
                chain.proceed(originalRequest)
            }
        }
        val loggingInterceptor = HttpLoggingInterceptor {
            Log.e("httpLog", it)
            if(it.length>4) {
                try {
                    val jsonObject = JSONObject(it)
                    val code = jsonObject.getInt("code")
                    if (code == 401) {//清除账号信息
                        SPUtils.getInstance().clear()
//                        MyApplication.application?.let { it1 -> CodeLoginActivity.startIntent(it1) }
                    }
                } catch (e: Exception) {
                    Log.e("aa", "---------清除账号信息异常：" + e.message)
                }
            }

        }
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        /**OkHttpClient*/
        val okHttpClient = OkHttpClient.Builder()
            .callTimeout(CALL_TIMEOUT, TimeUnit.SECONDS)
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(IO_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(IO_TIMEOUT, TimeUnit.SECONDS)
            .addInterceptor(AddCookiesInterceptor())
            .addInterceptor(ReceivedCookiesInterceptor())
            .addInterceptor(loggingInterceptor)
            .addInterceptor(mTokenInterceptor)
            .retryOnConnectionFailure(true)
            .build()

        /**Retrofit*/
        val retrofit = Retrofit.Builder()
            .baseUrl(Api.BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        /**ApiService*/
        apiService = retrofit.create(Api::class.java)
    }

}
